import { createApp, watchEffect } from 'vue';
import ElementPlusX from 'vue-element-plus-x';

import { registerAccessDirective } from '@vben/access';
import { preferences } from '@vben/preferences';
import { initStores } from '@vben/stores';
import '@vben/styles';
import '@vben/styles/ele';

import { useTitle } from '@vueuse/core';
import {
  ElCard,
  ElDropdown,
  ElDropdownItem,
  ElDropdownMenu,
  ElLoading,
  ElTag,
  ElTooltip,
  ElTree,
  ElUpload,
} from 'element-plus';

import FosoForm from '#/components/FosoForm/index.vue';
import FosoTabs from '#/components/FosoTabs/index.vue';
import { $t, setupI18n } from '#/locales';

import { initComponentAdapter } from './adapter/component';
import App from './app.vue';
import { router } from './router';

// 导入foso-table组件初始化
import '@vben/plugins/FosoTable/init';

async function bootstrap(namespace: string) {
  // 初始化组件适配器
  await initComponentAdapter();
  const app = createApp(App);

  // 注册Element Plus提供的v-loading指令
  app.directive('loading', ElLoading.directive);

  // 国际化 i18n 配置
  await setupI18n(app);

  // 配置 pinia-tore
  await initStores(app, { namespace });

  // 安装权限指令
  registerAccessDirective(app);

  // 配置路由及路由守卫
  app.use(router);

  app.use(ElementPlusX);
  app.component('ElDropdown', ElDropdown);
  app.component('ElDropdownMenu', ElDropdownMenu);
  app.component('ElDropdownItem', ElDropdownItem);
  app.component('ElTree', ElTree);
  app.component('ElTooltip', ElTooltip);
  app.component('ElCard', ElCard);
  app.component('FosoForm', FosoForm);
  app.component('ElUpload', ElUpload);
  app.component('FosoTabs', FosoTabs);
  app.component('ElTag', ElTag);
  // 动态更新标题
  watchEffect(() => {
    if (preferences.app.dynamicTitle) {
      const routeTitle = router.currentRoute.value.meta?.title;
      const pageTitle =
        (routeTitle ? `${$t(routeTitle)} - ` : '') + preferences.app.name;
      useTitle(pageTitle);
    }
  });

  app.mount('#app');
}

export { bootstrap };
